<template>
  <el-card header="分配菜单">
    <el-tree
      ref="tree"
      :props="treeProps"
      :data="treeData"
      :default-checked-keys="checkedKeys"
      node-key="id"
      show-checkbox
      default-expand-all>
    </el-tree>
    <div class="btn-wrapper">
      <el-button @click="handleReset">重置</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">提交</el-button>
    </div>
  </el-card>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import { getRoleResources, getResourceAll, getResourceCategory, saveOrUpdateResource } from '@/services/boss'
import { Message, Tree } from 'element-ui'

@Component
export default class AllowResource extends Vue {
  private treeProps = {
    label: 'name'
  }

  private treeData: any = []
  private checkedKeys: Array<number> = []
  private loading = false

  handleReset () {
    (this.$refs.tree as Tree).setCheckedKeys([])
  }

  async handleSubmit () {
    try {
      this.loading = true
      const params = {
        roleId: this.$route.params.roleId,
        resourceIdList: (this.$refs.tree as Tree).getCheckedKeys()
      }
      await saveOrUpdateResource(params)
      Message.success('分配成功')
      this.$router.back()
    } catch (e: any) {
      console.error(e)
      Message.error(e.message)
    } finally {
      this.loading = false
    }
  }

  async mounted () {
    let response = await getResourceCategory()
    const treeData = response.data
    response = await getResourceAll()
    response.data.forEach((r: any) => {
      const category = treeData.find((item: any) => item.id === r.categoryId)
      if (category) {
        category.children = category.children || []
        category.children.push(r)
      }
    })
    treeData.forEach((item: any) => {
      item.id = Math.random()
    })
    this.treeData = treeData
    const params = {
      roleId: this.$route.params.roleId
    }
    response = await getRoleResources(params)
    console.log(response.data)
    this.checkedKeys = response.data.map((item: any) => item.id)
  }
}
</script>

<style scoped>

</style>
